package com.fs.controller.v1;

import com.fs.controller.vo.PageData;
import com.fs.controller.vo.user.*;
import com.fs.global.init.RoleName;
import com.fs.service.UserService;
import com.fs.service.bo.BoPageInfo;
import com.fs.service.bo.user.BoSaveUser;
import com.fs.service.bo.user.BoUserInfo;
import com.fs.service.bo.user.BoUserInfoWithRole;
import com.fs.utils.Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "账户管理",description = "管理员账户使用")
@RestController
@RequestMapping("/v1/user")
@RequiresRoles(RoleName.ADMIN)
@Validated
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation("查询用户")
    @GetMapping
    public PageData<RespUserWithRole> queryUsers(ReqUserQuery queryDto) {

        BoUserInfo boUserInfo = new BoUserInfo();
        boUserInfo.setLoginName(queryDto.getLoginName());
        boUserInfo.setName(queryDto.getName());

        BoPageInfo<BoUserInfoWithRole> pageInfo =
                userService.queryUserInfoWithRoleByPage(boUserInfo, queryDto.getPageNo(), queryDto.getPageSize());

        PageData<RespUserWithRole> pageData = new PageData<>();
        pageData.setTotal(pageInfo.getTotal());

        List<RespUserWithRole> data = pageInfo.getResults().stream().map(RespUserWithRole::new).collect(Collectors.toList());
        pageData.setResults(data);
        return pageData;
    }

    @ApiOperation(value = "创建用户")
    @PostMapping
    public RespUser saveUser(@RequestBody @Valid ReqCreateUser user) {
        BoSaveUser param = new BoSaveUser();
        param.setLoginName(user.getLoginName());
        param.setName(user.getName());
        param.setPassword(user.getPassword());
        BoUserInfo boUserInfo = userService.saveUser(param);

        return new RespUser(boUserInfo);
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public void deleteUser(@ApiParam("用户id") @PathVariable Integer id) {
        userService.deleteUser(id);
    }

    @ApiOperation("给用户添加角色")
    @PostMapping("/role")
    public void bindRoleToUser(@RequestBody @Valid ReqAddRoles roles) {
        userService.addRoles(roles.getRoleIDs(),roles.getUserID());
    }
}
